﻿using Enterprise_Store.Data;

using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Popups;
using Windows.UI.ApplicationSettings;
using System.Collections.ObjectModel;
using Windows.Management.Deployment;
using Windows.Foundation;
using System.Threading;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Enterprise_Store.Common;
using Windows.UI.Xaml.Navigation;


// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231

namespace Enterprise_Store
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class GroupedItemsPage : Page
    {
        public static String feed1Name = "";
        public static String feed1URI = "";
        public static String feed2Name = "";
        public static String feed2URI = "";

        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        public GroupedItemsPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            SettingsPane.GetForCurrentView().CommandsRequested += SettingCharmManager_CommandsRequested;
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            Window.Current.SizeChanged += WindowSizeChanged;
        }


        private void WindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
        {
            manageDisplay(e.Size.Width);
        }

        private void manageDisplay(double Width)
        {
            if (Width <= 500)
            {
                InternalComFeedGridView.Visibility = Visibility.Collapsed;
                itemListView.Visibility = Visibility.Visible;
                itemGridView.Visibility = Visibility.Collapsed;
                pageTitleSnapped.Visibility = Visibility.Visible;
                pageTitle.Visibility = Visibility.Collapsed;
                backButton.Visibility = Visibility.Collapsed;
                backButtonSnapped.Visibility = Visibility.Visible;
            }
            else if (Width <= 900)
            {
                //disable the feeds if needed
                if ((int)Application.Current.Resources["nbFeeds"] != 0)
                {
                    InternalComFeedGridView.Visibility = Visibility.Collapsed;
                    this.ContentGrid.ColumnDefinitions.Clear();
                    var col1 = new ColumnDefinition();

                    col1.Width = new GridLength(0);
                    this.ContentGrid.ColumnDefinitions.Add(col1);

                    var col2 = new ColumnDefinition();

                    this.ContentGrid.ColumnDefinitions.Add(col2);
                    this.itemGridView.Padding = new Thickness(116, 0, 0, 0);
                }
                itemListView.Visibility = Visibility.Collapsed;
                itemGridView.Visibility = Visibility.Visible;
                pageTitleSnapped.Visibility = Visibility.Collapsed;
                pageTitle.Visibility = Visibility.Visible;
                backButton.Visibility = Visibility.Visible;
                backButtonSnapped.Visibility = Visibility.Collapsed;
            }
            else
            {
                //re-enable the feeds if needed
                if (ContentGrid.ColumnDefinitions[0].Width.Value == 0 && ((int)Application.Current.Resources["nbFeeds"] != 0))
                {
                    this.ContentGrid.ColumnDefinitions.Clear();
                    var col1 = new ColumnDefinition();

                    col1.Width = new GridLength(400);
                    this.ContentGrid.ColumnDefinitions.Add(col1);

                    var col2 = new ColumnDefinition();

                    this.ContentGrid.ColumnDefinitions.Add(col2);
                    this.itemGridView.Padding = new Thickness(0, 0, 0, 0);
                }
                InternalComFeedGridView.Visibility = Visibility.Visible;
                itemListView.Visibility = Visibility.Collapsed;
                itemGridView.Visibility = Visibility.Visible;
                pageTitleSnapped.Visibility = Visibility.Collapsed;
                pageTitle.Visibility = Visibility.Visible;
                backButton.Visibility = Visibility.Visible;
                backButtonSnapped.Visibility = Visibility.Collapsed;
            }

        }

        private void SettingCharmManager_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            if (App.displayPrivacyPolicy)
            {
                args.Request.ApplicationCommands.Clear();
                SettingsCommand cmd = new SettingsCommand("privacypolicy", "Privacy policy", (uiCommand) =>
                {
                    OpenPrivacyPolicy();
                });

                args.Request.ApplicationCommands.Add(cmd);

                cmd = new SettingsCommand("getthisapp", "Get this app for your customer", (uiCommand) =>
                {
                    GetThisApp();
                });

                args.Request.ApplicationCommands.Add(cmd);
            }
        }

        private async void OpenPrivacyPolicy()
        {
            Uri uri = new Uri("http://companystore.codeplex.com/wikipage?title=Privacy&version=1");
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private async void GetThisApp()
        {
            Uri uri = new Uri("http://companystore.codeplex.com/");
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            double tp = ((Window.Current.Bounds.Height - 206) / 120);
            
            String error = SampleDataSource.getError();
            if (error != null)
            {
                showError(error);
            }

            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var sampleDataGroups = SampleDataSource.GetGroups();
            this.DefaultViewModel["Groups"] = sampleDataGroups;

            //Display Feeds if there is valid feeds defined in the storestructure.xml
            if ((int)Application.Current.Resources["nbFeeds"]==0)
            {
                this.ContentGrid.ColumnDefinitions.Clear();
                var col1 = new ColumnDefinition();

                col1.Width = new GridLength(0);
                this.ContentGrid.ColumnDefinitions.Add(col1);

                var col2 = new ColumnDefinition();

                this.ContentGrid.ColumnDefinitions.Add(col2);
                
                this.itemGridView.Padding = new Thickness(116, 0, 0, 0);
            }
            else
            {
                var feedsDataGroups = FeedDataSource.GetGroups((int)Math.Round(tp / (int)Application.Current.Resources["nbFeeds"]));
                this.DefaultViewModel["RSSFeed"] = feedsDataGroups;
            }

            //set the new margin for the main grids
            string[] margin = App.itemGridViewMargin.Split(',');

            try
            {
                this.itemGridView.Margin = new Thickness(Double.Parse(margin[0]), Double.Parse(margin[1]), Double.Parse(margin[2]), Double.Parse(margin[3]));
                this.InternalComFeedGridView.Margin = new Thickness(Double.Parse(margin[0]), Double.Parse(margin[1]), Double.Parse(margin[2]), Double.Parse(margin[3]));
            }
            catch (Exception)
            {
                this.itemGridView.Margin = new Thickness(0, 0, 0, 0);
            }

            manageDisplay(Window.Current.Bounds.Width);

        }

        /// <summary>
        /// Invoked when a group header is clicked.
        /// </summary>
        /// <param name="sender">The Button used as a group header for the selected group.</param>
        /// <param name="e">Event data that describes how the click was initiated.</param>
        void Header_Click(object sender, RoutedEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(GroupDetailPage), ((SampleDataGroup)group).UniqueId);
        }

        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        async void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            String uri = ((SampleDataItem)e.ClickedItem).Description;
           
            var option = new Windows.System.LauncherOptions();
            if (((SampleDataItem)e.ClickedItem).Content != "")
            {
                option.PreferredApplicationPackageFamilyName = ((SampleDataItem)e.ClickedItem).Content;
                option.PreferredApplicationDisplayName = ((SampleDataItem)e.ClickedItem).Title;
            }
            if (uri.ToUpper().Contains("daipp://windowsStoreWin8app".ToUpper()) && !uri.ToUpper().Contains("storeid=".ToUpper()))
            {
                uri += "?storeid=" + ((SampleDataItem)e.ClickedItem).Content;
            }
            try
            {
                //If the URI is well formated go on, if not display the error message.                
                if (Uri.IsWellFormedUriString(uri, UriKind.Absolute) || uri.ToUpper().Contains("daipp://".ToUpper()))
                {
                    var result = await Windows.System.Launcher.LaunchUriAsync(new Uri(uri), option);
                    if (!result)
                    {
                        ((SampleDataItem)e.ClickedItem).Subtitle = String.Format("Error lauching {1}", uri);
                        if (((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed)
                        {
                            ((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed = true;
                        }
                    }
                }
                else
                {
                    ((SampleDataItem)e.ClickedItem).Subtitle = String.Format(App.errorURIMessage, uri);
                    if (((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed)
                    {
                        ((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed = true;
                    }
                }
            }
            catch (FormatException)
            {
                ((SampleDataItem)e.ClickedItem).Subtitle = String.Format(App.errorURIMessage, ((SampleDataItem)e.ClickedItem).Description);
                if (((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed)
                {
                    ((SampleDataItem)e.ClickedItem).ErrorAlreadyDisplayed = true;
                }
            }
        }

        /// <summary>
        /// Invoked when an item within a RSS feed is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        async void InternalComFeedGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page described in the item
            if(((SampleDataItem)e.ClickedItem).Description != ""){
                var uri = new Uri(((SampleDataItem)e.ClickedItem).Description);
                if(uri.IsWellFormedOriginalString())
                    await Windows.System.Launcher.LaunchUriAsync(uri);
            }
            
        }

        internal void showError(String msg)
        {
            ErrorMessage.Text = msg;
            ErrorCanvas.Visibility = 0;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            Application.Current.Exit();
        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion
    }
}
